﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SaveTheQueen.Actions;

namespace SaveTheQueen.Component
{
    public class AnimatedSprite : ImageSprite
    {
        private string[] resource;
        private Texture2D[] frames;
        private WaitAction frameChange;
        private float frameInterval;
        private int currentFrame;
        private bool cyclic;
        private bool ascending;

        public AnimatedSprite(string[] resource, float frameInterval, int x, int y, int w, int h, GameObject owner, Game game)
            : base(resource[0], x, y, w, h, owner, game)
        {
            this.resource = resource;
            this.frames = new Texture2D[resource.Length];
            this.frameInterval = frameInterval;
            this.currentFrame = 0;
            this.cyclic = true;
            this.ascending = true;

            frameChange = new WaitAction(game);
            frameChange.IsLopping = true;
            frameChange.Start(false, true, frameInterval);
            frameChange.OnUpdate += delegate() { };
            frameChange.OnFinished += NextFrame;

            this.Actions.Add(frameChange);
        }

        private void NextFrame()
        {
            if (cyclic)
            {
                if (ascending)
                {
                    if (currentFrame < frames.Length - 1)
                        currentFrame++;
                    else
                    {
                        currentFrame = frames.Length - 2;
                        ascending = false;
                    }
                }
                else
                {
                    if (currentFrame > 1)
                        currentFrame--;
                    else
                    {
                        currentFrame = 0;
                        ascending = true;
                    }
                }
                this.Texture = frames[currentFrame];
            }
            else
            {
                if (currentFrame < frames.Length - 1)
                    currentFrame++;
                else
                    currentFrame = 0;
            }
        }

        protected override void LoadContent()
        {
            for (int i = 0; i < frames.Length; i++)
                frames[i] = Game.Content.Load<Texture2D>(resource[i]);
            base.LoadContent();
        }
        protected override void UnloadContent()
        {
            for (int i = 0; i < frames.Length; i++)
                frames[i].Dispose();
            base.UnloadContent();
        }
    }
}
